package http

import (
	"fmt"
	"go2/pool"
	"io"
	"net/http"
)

// A ResponseWriter interface is used by an HTTP handler to
// construct an HTTP Response.
//
// A ResponseWriter may not be used after the Handler.ServeHTTP method
// has returned.
type Response struct {
	header      http.Header
	status      int
	conn        io.Writer
	head_writed bool
	pro_id      int
}

func NewResponse2(conn io.Writer, pro_id int) *Response {
	return &Response{
		header:      make(http.Header),
		conn:        conn,
		status:      0,
		head_writed: false,
		pro_id:      pro_id,
	}
}

func (c *Response) ProID() int {
	return c.pro_id
}

func (c *Response) Header() http.Header {
	return c.header
}

func (c *Response) GetHeaderLen() (n int) {
	n = 0

	for k, v := range c.header {
		n += len(k) + 2
		for k1, v1 := range v {
			n += len(v1)
			if k1 > 0 {
				n += 2
			}
		}
		n += 2
	}
	return n + 2
}

func (c *Response) GetHeaderData(data_head *[]byte) {
	for k, v := range c.header {
		*data_head = append(*data_head, k+": "...)
		for k1, v1 := range v {
			*data_head = append(*data_head, v1...)
			if k1 > 0 {
				*data_head = append(*data_head, "; "...)
			}
		}
		*data_head = append(*data_head, "\r\n"...)
	}
	*data_head = append(*data_head, "\r\n"...)
}

func (c *Response) Write(data []byte) (int, error) {
	return c.conn.Write(data)
}

func (c *Response) WriteHeader(statusCode int) {
	c.status = statusCode

	data_head := pool.Malloc(c.GetHeaderLen() + 128)
	defer pool.Free(data_head)

	data_head = []byte(fmt.Sprintf("HTTP/1.1 %d %s\r\n", c.status, http.StatusText(c.status)))
	c.GetHeaderData(&data_head)

	c.conn.Write(data_head)
}
